import { onBeforeUnmount, ref } from 'vue'
import { themeLocal } from '@/storage/local'
import { addClass, CoreListener, removeClass } from '@lhy-assist/utils'

/**
 * 主题
 */
export enum Theme {
  // 亮色
  Light = 'light',
  // 暗黑
  Dark = 'dark',
}

// 当前主题
export const theme = ref(themeLocal.get() || Theme.Light)
const themeChangeListener = new CoreListener<Theme>()

/**
 * 切换主题
 * @param newTheme
 */
export function toggleTheme(newTheme?: Theme) {
  if (!newTheme) {
    newTheme = theme.value === Theme.Light ? Theme.Dark : Theme.Light
  }
  removeClass(document.documentElement, theme.value)
  addClass(document.documentElement, newTheme)
  document.documentElement.setAttribute('theme', newTheme)
  theme.value = newTheme
  themeLocal.set(newTheme)
  themeChangeListener.emit(theme.value)
}

toggleTheme(theme.value)

/**
 * 主题服务
 */
export function useThemeService(options?: { onThemeChange: (theme: Theme) => void }) {
  if (options?.onThemeChange) {
    themeChangeListener.on(options.onThemeChange)

    onBeforeUnmount(() => themeChangeListener.off(options.onThemeChange))
  }

  return {
    theme,
    toggleTheme,
  }
}
